# -*- coding: utf-8 -*-
from pydub import AudioSegment
from pydub.utils import make_chunks
import io, os

'''
author: hao.liu
date: 2019-07-21
desc: wav cutter by cue 
'''

CUE = 'cd1.cue'
WAV = 'cd1.wav'

fp = io.open(CUE,'r',encoding='utf-8')
cue = []
song = {}
for line in fp.readlines():
  text = line.strip()
 

  if text[:5]=='TRACK':
    song = {}
    continue

  if text[:5]=='TITLE':
    song['TITLE']= text[7:-1]
    continue

  if text[:9]=='PERFORMER':
    song['PERFORMER'] = text[11:-1]
    continue


  if text[:8]=='INDEX 00':
    song['INDEX00'] = text[9:]
    continue  

  if text[:8]=='INDEX 01':
    song['INDEX01'] = text[9:]
  
  if len(song.keys())==4:
    cue.append(song)  

fp.close  

for i in range(len(cue)):
  m = int(cue[i]['INDEX00'][:2])
  s = int(cue[i]['INDEX00'][3:5])
  ms = int(cue[i]['INDEX00'][6:8])
  cue[i]['INDEX00'] = (m*60+s)*1000+ms

  m = int(cue[i]['INDEX01'][:2])
  s = int(cue[i]['INDEX01'][3:5])
  ms = int(cue[i]['INDEX01'][6:8])
  cue[i]['INDEX01'] = (m*60+s)*1000+ms
  cue[i]['TITLE'] = '%s - %s.mp3' % (cue[i]['PERFORMER'],cue[i]['TITLE'])


wav = AudioSegment.from_file(WAV)
for i in range(len(cue)):
  begin = cue[i]['INDEX00']
  finish = cue[i]['INDEX01']
  song = wav[begin:finish]
  song.export(cue[i]['TITLE'],format='mp3')

